package com.laysonx.data.police.core;

import com.laysonx.data.police.annotation.EnableDataPolice;
import com.laysonx.data.police.util.BeanDefinitionUtil;
import com.laysonx.data.police.util.CheckUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.List;


/**
 * 注册处理器
 * @author: Laysonx
 * @date: 2019/9/27 16:18
 */
public class DataPoliceRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware,BeanFactoryAware {

    private ResourceLoader resourceLoader;

    private BeanFactory beanFactory;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata
                .getAnnotationAttributes(EnableDataPolice.class.getName()));
        String[] scanHelperPackages = attributes.getStringArray("scanHelperPackages");
        String pointcut = attributes.getString("pointcut");

        AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(importingClassMetadata)).getPackageName());
        List<String> defaultPackages = AutoConfigurationPackages.get(this.beanFactory);
        defaultPackages.addAll(Arrays.asList(scanHelperPackages));
        String[] scanPackages = new String[]{};
        scanPackages = defaultPackages.toArray(scanPackages);

        // 检查扫描路径、切点等初始化参数
        CheckUtil.checkInitParams(scanPackages,pointcut);

        // 扫描@DataHelper
        BeanDefinitionUtil.scanDataHelper(registry,resourceLoader,scanPackages);

        // 初始化所需beanDefinition
        BeanDefinitionUtil.initBean(registry,pointcut);
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

}
